package com.ccnf.service.impl;

import com.ccnf.core.exception.BizException;
import com.ccnf.core.utils.ResultUtil;
import com.ccnf.model.entity.AccountRecord;
import com.ccnf.model.entity.InvitationAccount;
import com.ccnf.model.entity.RewardCash;
import com.ccnf.model.mapper.AccountRecordMapper;
import com.ccnf.model.mapper.InvitationAccountMapper;
import com.ccnf.model.mapper.RewardCashMapper;
import com.ccnf.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private InvitationAccountMapper invitationAccountMapper;
    @Autowired
    private AccountRecordMapper accountRecordMapper;
    @Autowired
    private RewardCashMapper rewardCashMapper;

    @Override
    public InvitationAccount findInvitationAccountByAccountId(Long accountId) {
        return invitationAccountMapper.selectById(accountId);
    }

    @Override
    public InvitationAccount findUserInvitationAccount(Long invitationId, Long userId) {
        return invitationAccountMapper.selectByInvitationIdAndUserId(invitationId, userId);
    }

    @Override
    public List<AccountRecord> findAccountIncomeDetailByAccountId(Long accountId) {
        return accountRecordMapper.selectAccountIncomeDetailByAccountId(accountId);
    }

    @Override
    @Transactional
    public Long saveRewardAccountCash(RewardCash rewardCash) {
        ResultUtil.validateSQL(invitationAccountMapper.reduceAccountMoney(rewardCash.getAccountId(), rewardCash.getCashAmount()), "提现失败");
        ResultUtil.validateSQL(rewardCashMapper.insert(rewardCash), "提现失败");
        return rewardCash.getCashId();
    }

    @Override
    public void modifyRewardAccountCashByCashId(RewardCash rewardCash) {
        Integer isCash = rewardCash.getIsCash();// 是否提现红包成功（0：否，1：是）
        if (isCash == null) {
            throw new BizException("提现状态isCash为null");
        }
        if (isCash == 0) {
            // 提现红包失败
            invitationAccountMapper.addAccountMoney(rewardCash.getAccountId(), rewardCash.getCashAmount());
        } else {
            rewardCashMapper.updateById(rewardCash);
        }
    }

    @Override
    public List<RewardCash> findAccountCashDetailByAccountId(Long accountId) {
        return rewardCashMapper.selectAccountCashDetailByAccountId(accountId);
    }
}